package com.zlx.mall.biz.access.aspect;

import com.zlx.mall.basic.annotations.ValidateIp;
import com.zlx.mall.basic.common.exception.IllegalBizArgumentException;
import com.zlx.mall.basic.resource.IResourceService;
import com.zlx.mall.basic.util.net.SubnetUtil;
import com.zlx.mall.basic.web.holder.RequestContextHolder;
import com.zlx.mall.biz.access.enums.AccessResourceEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Aspect
@Component
@Order(-1)
public class IpAspect {

    @Resource
    private IResourceService resourceService;

    @Pointcut(value = "(@annotation(org.springframework.web.bind.annotation.RequestMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.PostMapping)) " +
            "||@annotation(org.springframework.web.bind.annotation.GetMapping)")
    private void pointcut() {
    }

    @Before("pointcut()")
    public void doBefore(JoinPoint point) {
        ValidateIp annotation = ((MethodSignature) point.getSignature()).getMethod().getAnnotation(ValidateIp.class);

        if (annotation != null) {
            String allowAddress = resourceService.get(AccessResourceEnum.ALLOW_IP, String.class,"");
            if (!SubnetUtil.checkAllowAddress(allowAddress,RequestContextHolder.getRemoteAddress())){
                throw new IllegalBizArgumentException("ip不在白名单");
            }
        }
    }

}
